import { injectable, inject } from 'inversify';
import WebSocket, { WebSocketServer } from 'ws';
import { ConfigService } from '../../infrastructure/config/config.service';
import { LoggerService } from '../../infrastructure/logging/logger.service';
import { WsHandler } from './ws.handler';
import { TYPES } from '../../infrastructure/ioc/types';

@injectable()
export class WsServer {
  private wss: WebSocketServer;

  constructor(
    @inject(TYPES.ConfigService) private configService: ConfigService,
    @inject(TYPES.LoggerService) private logger: LoggerService,
    @inject(TYPES.WsHandler) private wsHandler: WsHandler
  ) {
    this.wss = new WebSocketServer({ port: this.configService.getWebsocketPort() });
    this.initialize();
  }

  private initialize() {
    this.wss.on('connection', (ws: WebSocket) => {
      this.wsHandler.handleConnection(ws);
    });

    this.wss.on('error', (error) => {
      this.logger.error(`WebSocket error: ${error.message}`);
    });

    this.logger.info(`WebSocket server started on port ${this.configService.getWebsocketPort()}`);
  }
}
